package com.api.client;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;


public class VariablePath {
	
	private static final String LEFT_REF = "{";
	private static final String RIGHT_REF = "}";
	
	private final List<String> vars = new ArrayList<String>();
	
	private final String path;

	
	public VariablePath(String path){
		
		this.path = path;
		
		String[] split = path.split("/");
		for(int i = 0; i < split.length ; i++){
				
			String str = split[i];
			extractReferenceVariable(str);
		}
	}
	
	private void extractReferenceVariable(String str) {
		
		if(str.startsWith(LEFT_REF) && str.endsWith(RIGHT_REF)){
			
			String ref = str.substring(1, str.length() - 1);
			if(!ref.equals("") && !vars.contains(ref)){
				vars.add(ref);
			}
			else
				throw new IllegalArgumentException(String.format("Reference value '%s' is empty or duplicated", str));
		}
	}

	public String getRealPath(Object... values){
		
		String url = path;
		int i = 0;
		
		if (values != null){
		
			while (i < vars.size() && i < values.length){
				url = url.replace(LEFT_REF + vars.get(i) + RIGHT_REF, String.valueOf(values[i]));
				i++;
			}
		}
		if(i >= vars.size()){
			return url;
		}
		else
			throw new IllegalArgumentException(String.format("Path variables missing: '%s'", url));
	}
	
	public int getVariablesCount(){
		return vars.size();
	}
	
	public List<String> getVariables(){
		return Collections.unmodifiableList(vars);
	}
	
	public String getRealPath(Map<String, Object> params){
		
		String url = path;
		
		for(String pathParam: vars){
			
			if(params.containsKey(pathParam)){
				
				Object value = params.get(pathParam);
				String pathValue = String.valueOf(value);
				
				url = url.replace(LEFT_REF + pathParam + RIGHT_REF, pathValue);
			}
			else
				throw new IllegalArgumentException(String.format("Couldn't get real path from variable path. Parameter '%s' is missing", pathParam));
		}
		return url;
	}
}
